package logic

import (
	"encoding/json"
	"fmt"
	"iot-base/auth/db"
	"iot-base/auth/model/iot"
	"iot-base/auth/svc"
	types2 "iot-base/auth/types"
	"time"
)

type ThingLogic struct {
}

func NewThingLogic() *ThingLogic {
	return &ThingLogic{}
}

// ThingList 设备列表.
func (l *ThingLogic) ThingList(thingId string) ([]iot.Thing, error) {
	result, err := svc.Dao.TThings.FindStationsThing(thingId, false)
	return result, err
}

func (l *ThingLogic) GetThingService(thingIds []string) (map[string]any, error) {
	things, err := svc.Dao.TThings.WhereInId(thingIds)
	if err != nil {
		return nil, err
	}
	thingNum := len(things)
	if thingNum == 0 {
		return nil, nil
	}
	var modelIds = make([]string, 0, thingNum)
	for index := range things {
		modelIds = append(modelIds, things[index].ModelID)
	}
	models, err := svc.Dao.TTModel.WhereInId(modelIds)
	if err != nil {
		return nil, err
	}
	modelNum := len(models)
	if modelNum == 0 {
		return nil, nil
	}
	service := make(map[string]any)
	for i := range models {
		b, err := models[i].Body.MarshalJSON()
		if err != nil {
			continue
		}
		var body map[string]any
		err = json.Unmarshal(b, &body)
		if err != nil {
			continue
		}
		data := make(map[string]any)
		data["model_id"] = models[i].UID
		data["model_name"] = models[i].SName
		if v, ok := body["services"]; ok {
			data["services"] = v
		} else {
			data["services"] = []any{}
		}
		service[models[i].UID] = data
	}
	return service, nil
}

func GetGasStationEdgeId(stationId string) string {
	key := fmt.Sprintf("stationId#edgeId#%v", stationId)
	redis := db.NewRedis()
	edgeId, _ := redis.Get(key)
	if edgeId != "" {
		return edgeId
	}
	if edgeId == db.RedisNull {
		return ""
	}
	thingId, _ := NewStationLogic().GetThingIdByStationIdAndModelId(stationId, types2.CaloModelId)
	thing, err := svc.Dao.TThings.GetThingById(thingId)
	if err != nil {
		_, err = redis.Set(key, db.RedisNull, time.Second*3)
		return ""
	}

	edgeId = thing.ProxyThingID
	if edgeId == "" {
		_, err = redis.Set(key, db.RedisNull, time.Second*3)
		return ""
	}

	_, err = redis.Set(key, edgeId, time.Hour)
	return edgeId
}
